package jeesample.jaxrs;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;

import jeesample.dtos.EchoDTO;
import jeesample.service.publishers.EchoServicePublisher;

import org.apache.log4j.Logger;
import org.glassfish.jersey.server.JSONP;

@Path("echo")
public class EchoRS extends BaseRESTfulService {
	private Logger logger = Logger.getLogger(getClass());

	@Override
	protected Logger logger() {
		// TODO Auto-generated method stub
		return logger;
	}

	private EchoServicePublisher publisher = new EchoServicePublisher();

	@GET
	@Path("/ping/{userId}")
	@JSONP
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public EchoDTO ping(@PathParam("userId") final String userId,
			@Context HttpServletRequest request) {
		dbg("ping(" + userId + ")");

		StringBuilder sb = new StringBuilder();

		sb.append("\nUser Principal:");
		Principal principal = request.getUserPrincipal();
		if (principal != null) {
			sb.append(principal.getName());
		}

		sb.append("\nPing info:");
		sb.append(publisher.ping(userId));

		EchoDTO dto = new EchoDTO(sb.toString());
		dto.fill(request);
		return dto;
	}

	@GET
	@Path("/dump")
	@JSONP
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public EchoDTO dump(@Context UriInfo uriInfo, @Context HttpHeaders headers,
			@Context HttpServletRequest request,
			@Context SecurityContext securityContext) {
		dbg("dump()");
		StringBuilder sb = new StringBuilder(1024 * 4);

		sb.append("\nHTTP Headers are as below:\n");
		for (String header : headers.getRequestHeaders().keySet()) {
			sb.append(header);
			sb.append(':');
			sb.append(headers.getRequestHeader(header).get(0));
			sb.append('\n');
		}

		EchoDTO dto = new EchoDTO(sb.toString());
		dto.fill(uriInfo);
		dto.fill(request);
		dto.fill(securityContext);
		return dto;
	}

}
